<!--
 * @Author: 冕上 cxm66888@163.com
 * @Date: 2025-01-01 00:00:00
 * @LastEditors: 冕上 cxm66888@163.com
 * @LastEditTime: 2025-08-07 21:55:41
 * @Description: 礼品管理
 * 
 * Copyright (c) 2025 by xiaoMing.Cao, All Rights Reserved. 
-->
<template>
  <div class="app-container">
    <!-- 统计信息 -->
    <div class="stats-container">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stats-card" @click="filterByType('')">
            <div class="stats-item">
              <div class="stats-number">{{ stats.total || 0 }}</div>
              <div class="stats-label">总礼品数</div>
              <div class="stats-tip">点击查看全部</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card" @click="filterByType('vip')">
            <div class="stats-item">
              <div class="stats-number">{{ stats.vip || 0 }}</div>
              <div class="stats-label">会员礼品</div>
              <div class="stats-tip">点击筛选会员类型</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card" @click="filterByType('real')">
            <div class="stats-item">
              <div class="stats-number">{{ stats.real || 0 }}</div>
              <div class="stats-label">实物礼品</div>
              <div class="stats-tip">点击筛选实物类型</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card" @click="filterByType('headwear')">
            <div class="stats-item">
              <div class="stats-number">{{ stats.headwear || 0 }}</div>
              <div class="stats-label">头饰礼品</div>
              <div class="stats-tip">点击筛选头饰类型</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="请输入礼品名称" style="width: 200px" class="filter-item" @keyup.enter="handleFilter" />
      <el-select v-model="listQuery.categoryId" placeholder="选择分类" clearable style="width: 200px" class="filter-item">
        <el-option v-for="item in categoryOptions" :key="item._id" :label="item.name" :value="item._id">
          <div class="category-option">
            <span>{{ item.name }}</span>
            <el-icon color="#333" @click.stop="handleDeleteCategory(item)"><Close /></el-icon>
          </div>
        </el-option>
      </el-select>
      <el-select v-model="listQuery.type" placeholder="选择类型" clearable style="width: 120px" class="filter-item">
        <el-option label="会员" value="vip" />
        <el-option label="实物" value="real" />
        <el-option label="头饰" value="headwear" />
      </el-select>
      <el-select v-model="listQuery.status" placeholder="状态" clearable style="width: 120px" class="filter-item">
        <el-option label="上架" :value="'active'" />
        <el-option label="下架" :value="'inactive'" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="Search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" type="warning" icon="Refresh" @click="handleRefresh">重置刷新</el-button>
      <el-button class="filter-item" type="success" icon="Plus" @click="handleCreate">新增礼品</el-button>
    </div>

    <el-table v-loading="listLoading" :data="list" element-loading-text="Loading..." border fit highlight-current-row>
      <el-table-column align="center" type="index" label="序号" width="95">
        <template #default="scope">
          {{ (listQuery.pageIndex - 1) * listQuery.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="礼品图片" width="120" align="center">
        <template #default="scope">
          <el-image :src="scope.row.imageUrl" style="width: 80px; height: 80px" fit="cover" :z-index="99999" preview-teleported :preview-src-list="[scope.row.imageUrl]" />
        </template>
      </el-table-column>
      <el-table-column label="礼品名称" align="center" min-width="150">
        <template #default="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" width="120">
        <template #default="scope">
          <el-tag :type="getTypeTagType(scope.row.type)">
            {{ getTypeLabel(scope.row.type) }}
          </el-tag>
          <div v-if="scope.row.type === 'vip'" class="type-detail">
            <small>{{ scope.row.vipTime || 0 }}天</small>
          </div>
          <div v-else-if="scope.row.type === 'headwear'" class="type-detail">
            <small>{{ scope.row.headwearId || '未选择' }}</small>
          </div>
          <div v-else-if="scope.row.type === 'real'" class="type-detail">
            <small>实物礼品</small>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="所属分类" align="center" width="120">
        <template #default="scope">
          {{ scope.row.categoryName }}
        </template>
      </el-table-column>
      <el-table-column label="兑换金币" align="center" width="100">
        <template #default="scope">
          <span class="coin-text">{{ scope.row.coins }}</span>
        </template>
      </el-table-column>
      <el-table-column label="补差金额" align="center" width="100">
        <template #default="scope">
          <span v-if="scope.row.additionalAmount > 0" class="amount-text">¥{{ scope.row.additionalAmount }}</span>
          <span v-else class="no-amount">-</span>
        </template>
      </el-table-column>
      <el-table-column label="库存" align="center" width="80">
        <template #default="scope">
          <span :class="scope.row.stock <= 10 ? 'stock-warning' : 'stock-normal'">{{ scope.row.stock }}</span>
        </template>
      </el-table-column>
      <el-table-column label="已兑换人数" align="center" width="120">
        <template #default="scope">
          {{ scope.row.exchangeCount || 0 }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
            {{ scope.row.status === 'active' ? '上架' : '下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" width="180">
        <template #default="scope">
          {{ scope.row.createdTime }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="280">
        <template #default="scope">
          <el-button size="small" type="primary" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="small" :type="scope.row.status === 'active' ? 'warning' : 'success'" @click="handleToggleStatus(scope.row)">
            {{ scope.row.status === 'active' ? '下架' : '上架' }}
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination style="margin-top: 15px; background: #fff; padding: 10px" :page-size="listQuery.pageSize" @change="handlePageChange" background layout="prev, pager, next" :total="total" />

    <!-- 删除分类确认弹窗 -->
    <el-dialog v-model="showDeleteDialog" title="删除分类" width="400px" :close-on-click-modal="false">
      <div class="delete-confirm">
        <el-icon class="warning-icon"><Warning /></el-icon>
        <p>
          确定要删除分类 "
          <strong>{{ selectedCategoryName }}</strong>
          " 吗？
        </p>
        <p class="warning-text">删除后无法恢复，请谨慎操作！</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDeleteDialog = false">取消</el-button>
          <el-button type="danger" @click="confirmDeleteCategory">确定删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { Warning, Close } from '@element-plus/icons-vue';
  import { getGiftList, deleteGift, toggleGiftStatus, getGiftCategories, deleteGiftCategory } from '@/api/gift';

  const router = useRouter();

  const list = ref([]);
  const total = ref(0);
  const listLoading = ref(true);
  const categoryOptions = ref([]);
  const showDeleteDialog = ref(false);
  const selectedCategoryName = ref('');
  const selectedCategoryId = ref('');
  const stats = ref({
    total: 0,
    vip: 0,
    real: 0,
    headwear: 0
  });

  const listQuery = reactive({
    pageIndex: 1,
    pageSize: 20,
    name: '',
    categoryId: '',
    status: '',
    type: '' // 新增类型筛选
  });

  const handlePageChange = page => {
    listQuery.pageIndex = page;
    getList();
  };

  const getList = async () => {
    listLoading.value = true;
    try {
      const response = await getGiftList(listQuery);
      if (response.code === 200) {
        list.value = response.data.list;
        total.value = response.data.total;

        // 查全部的时候，才计算统计数据
        if (listQuery.type === '') {
          calculateStats();
        }
      }
    } catch (error) {
      console.error('获取礼品列表失败:', error);
      ElMessage.error('获取礼品列表失败');
    } finally {
      listLoading.value = false;
    }
  };

  const calculateStats = () => {
    const typeCount = {
      vip: 0,
      real: 0,
      headwear: 0
    };

    list.value.forEach(item => {
      if (typeCount.hasOwnProperty(item.type)) {
        typeCount[item.type]++;
      }
    });

    stats.value = {
      total: list.value.length,
      vip: typeCount.vip,
      real: typeCount.real,
      headwear: typeCount.headwear
    };
  };

  const filterByType = type => {
    listQuery.type = type;
    listQuery.pageIndex = 1;
    getList();
  };

  const getCategories = async () => {
    try {
      const response = await getGiftCategories();
      if (response.code === 200) {
        categoryOptions.value = response.data.list;
      }
    } catch (error) {
      console.error('获取分类列表失败:', error);
    }
  };

  const handleFilter = () => {
    listQuery.pageIndex = 1;
    getList();
  };

  const handleCreate = () => {
    router.push('/gift/create');
  };

  const handleUpdate = row => {
    router.push(`/gift/edit/${row._id}`);
  };

  const handleToggleStatus = row => {
    const action = row.status === 'active' ? '下架' : '上架';
    ElMessageBox.confirm(`确定要${action}礼品"${row.name}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        const newStatus = row.status === 'active' ? 'inactive' : 'active';
        const response = await toggleGiftStatus(row._id, newStatus);
        if (response.code === 200) {
          ElMessage.success(`${action}成功`);
          getList();
        } else {
          ElMessage.error(response.msg || `${action}失败`);
        }
      } catch (error) {
        console.error(`${action}礼品失败:`, error);
        ElMessage.error(`${action}失败`);
      }
    });
  };

  const handleDelete = row => {
    ElMessageBox.confirm(`确定要删除礼品"${row.name}"吗？删除后无法恢复！`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        const response = await deleteGift(row._id);
        if (response.code === 200) {
          ElMessage.success('删除成功');
          getList();
        } else {
          ElMessage.error(response.msg || '删除失败');
        }
      } catch (error) {
        console.error('删除礼品失败:', error);
        ElMessage.error('删除失败');
      }
    });
  };

  const handleDeleteCategory = async item => {
    selectedCategoryName.value = item.name;
    selectedCategoryId.value = item._id; // 存储要删除的分类ID
    showDeleteDialog.value = true;
  };

  const confirmDeleteCategory = async () => {
    try {
      const response = await deleteGiftCategory(selectedCategoryId.value);
      if (response.code === 200) {
        ElMessage.success('分类删除成功');
        showDeleteDialog.value = false;

        // 如果删除的是当前选中的分类，则清空选择
        if (listQuery.categoryId === selectedCategoryId.value) {
          listQuery.categoryId = '';
          ElMessage.warning('已删除当前选中的分类，请重新选择');
        }

        // 重新获取分类列表
        await getCategories();
      } else {
        ElMessage.error(response.msg || '删除分类失败');
      }
    } catch (error) {
      console.error('删除分类失败:', error);
      ElMessage.error('删除分类失败');
    }
  };

  const handleRefresh = () => {
    listQuery.pageIndex = 1;
    listQuery.pageSize = 20;
    listQuery.name = '';
    listQuery.categoryId = '';
    listQuery.status = '';
    listQuery.type = ''; // 重置类型筛选
    getList();
  };

  // 获取类型标签
  const getTypeLabel = type => {
    const typeMap = {
      vip: '会员',
      real: '实物',
      headwear: '头饰'
    };
    return typeMap[type] || '未知';
  };

  // 获取类型标签颜色
  const getTypeTagType = type => {
    const typeColorMap = {
      vip: 'warning',
      real: 'primary',
      headwear: 'success'
    };
    return typeColorMap[type] || 'info';
  };

  onMounted(() => {
    getList();
    getCategories();
  });
</script>

<style scoped>
  .filter-container {
    padding-bottom: 10px;
  }

  .filter-item {
    margin-right: 10px;
  }

  .coin-text {
    color: #f56c6c;
    font-weight: bold;
  }

  .amount-text {
    color: #67c23a;
    font-weight: bold;
  }

  .no-amount {
    color: #909399;
  }

  .stock-normal {
    color: #67c23a;
  }

  .stock-warning {
    color: #e6a23c;
    font-weight: bold;
  }

  .category-option {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
  }

  .delete-confirm {
    text-align: center;
    padding: 20px 0;
  }

  .warning-icon {
    font-size: 48px;
    color: #e6a23c;
    margin-bottom: 16px;
  }

  .warning-text {
    color: #f56c6c;
    font-size: 14px;
    margin-top: 8px;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }

  .type-detail {
    margin-top: 4px;
    color: #909399;
    font-size: 12px;
  }

  /* 统计卡片样式 */
  .stats-container {
    margin-bottom: 20px;
  }

  .stats-card {
    text-align: center;
    cursor: pointer;
    transition: all 0.3s;
  }

  .stats-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  .stats-card:nth-child(1) .stats-number {
    color: #409eff; /* 总览 - 蓝色 */
  }

  .stats-card:nth-child(2) .stats-number {
    color: #e6a23c; /* 会员 - 橙色 */
  }

  .stats-card:nth-child(3) .stats-number {
    color: #67c23a; /* 实物 - 绿色 */
  }

  .stats-card:nth-child(4) .stats-number {
    color: #f56c6c; /* 头饰 - 红色 */
  }

  .stats-item {
    padding: 10px;
  }

  .stats-number {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 8px;
  }

  .stats-label {
    font-size: 14px;
    color: #606266;
  }

  .stats-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
  }
</style>
